package com.cg.asm.core.config.mvc;

import com.cg.asm.license.holder.LicenseVerifyHolder;
import com.cg.asm.license.verify.LicenseVerify;
import com.cg.asm.core.config.loading.StartupLoading;
import com.cg.asm.core.util.AsmApiUtils;
import com.cg.asm.client.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 访问控制拦截器
 */
public class AccessControlConfigurer implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) {
        String requestURI = httpServletRequest.getRequestURI();
        if(StringUtils.isNoneEmpty(requestURI) && requestURI.indexOf("/login/loginOutSuccess") != -1){
            // 【/login/loginOutSuccess】为Security转发方法，存在跨域情况，在此放行
            httpServletResponse.addHeader("Access-Control-Allow-Origin", "*"); //可以访问此域资源的域
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length,X-Requested-With,Host-Url,Authentication-Token,Cache-Control");
            httpServletResponse.addHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); //可以访问此域的脚本方法类型
            httpServletResponse.addHeader("X-Powered-By", "Jetty");
            String method = httpServletRequest.getMethod();
            if (method.equals("OPTIONS")) {
                httpServletResponse.setStatus(200);
                return false;
            }
        }
        try {
            LicenseVerify lv = LicenseVerifyHolder.getLicenseVerify(StartupLoading.licenseInputStream);
            String resultValue = lv.verify();
            if (!"success".equals(resultValue)) {
                try {
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter out = httpServletResponse.getWriter();
                    AsmApiUtils.outPrintlnByJSONObject(out, CommonUtil.errorJson("", "License已经过期, 请更新License"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

    }
}
